package myjava.algorithm.leetcode;

public class MergeSortArray {
    public static void merge(int A[], int m, int B[], int n) {
        int[] C = new int[m];

        for(int i=0;i<m;i++) {
            C[i]=A[i];
        }
        
        int pB = 0;
        int pA = 0;
        int index = 0;
        
        while(true) {
            if(pA > m-1 || pB > n-1 ) break;
            
            if(B[pB] < C[pA]) {
                A[index++] = B[pB];
                pB++;
            }
            else if(B[pB] == C[pA]) {
                A[index++] = B[pB];
                A[index++] = C[pA];
                pB++;
                pA++;
            }
            else if(B[pB] > C[pA]) {
                A[index++] = C[pA];
                pA++;
            }
        }

        if(pA > m - 1){
            while(true){
                if(pB > n-1) break;

                A[index++]=B[pB++];
            }
        }
        else if(pB > n-1){
            while(true){
                if(pA > m-1) break;

                A[index++]=C[pA++];
            }
        }
        /*
        for(int i=0;i<index;i++) {
            System.out.print(A[i] + " ");
        }
        */
    }

    public static void main(String[] args) {
        int A[] = {1,2,3,5,0,0,0,0};
        int B[]=  {1,2,4,6};
        merge(A,4,B,4);
    }
}
